package com.example.experiment_six_server;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {
    TextView tv_main_content;
    Handler handler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_main_content=(TextView)findViewById(R.id.tv_main_content);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0x123:
                        tv_main_content.setText(tv_main_content.getText().toString() + "\n" + msg.getData().getString("new_content"));
                }
            }
        };
        new Thread(new MyServer(handler)).start();
    }
}
class MyServer implements Runnable{
    public static ArrayList<Socket> socketList=null;
    Handler handler;
    public MyServer(Handler handler){
        this.handler=handler;
        socketList=new ArrayList<>();
    }
    @Override
    public void run(){
        try{
            ServerSocket ss = new ServerSocket(30000);
            while(true){
                //此行代码会堵塞，将一直等待别人的连接
                Socket s = ss.accept();
                socketList.add(s);
                //每当客户端连接后启动一条ServerThread线程为该客户端服务
                new Thread(new ServerThread(s,handler)).start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
//负责处理每条线程通信的线程类
class ServerThread implements Runnable{
    Socket s=null;
    BufferedReader br = null;
    Handler handler=null;
    public ServerThread(Socket s,Handler handler)
            throws IOException {
        this.s=s;
        this.handler=handler;
        br = new BufferedReader(new InputStreamReader(s.getInputStream(),"utf-8"));
    }
    @Override
    public void run(){
            String content = null;
            while ((content = readFromClient()) != null) {
                Message msg = new Message();
                msg.what = 0x123;
                Bundle bundle = new Bundle();
                bundle.putString("new_content", content);
                msg.setData(bundle);
                handler.sendMessage(msg);
                for (Iterator<Socket> it = MyServer.socketList.iterator(); it.hasNext(); ) {
                    Socket s = it.next();
                    try {
                        OutputStream os = s.getOutputStream();
                        os.write((content + "\n").getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                        //删除Socket
                        it.remove();
                        //System.out.println(MyServer.socketList);
                    }
                }
            }
    }
    //定义读取客户端数据的方法
    private String readFromClient(){
        try{
            return br.readLine();
        }
        catch (IOException e){
            e.printStackTrace();
            MyServer.socketList.remove(s);
        }
        return null;
    }
}
